<script setup>
import { onBeforeUnmount, watchEffect, ref } from 'vue';
import Recorder from './Recorder.js'
import CAudio from './audio.vue'

const modelValue = defineModel()
const isRecording = ref(false)
const recordTime = ref(0)
const emit = defineEmits(['update:modelValue','voice'])
const recorder = new Recorder({recordTime: 60, unlimited: false, onEnd: () => {
    isRecording.value = false
    url.value = window.URL.createObjectURL(recorder.getBlob())
}})
const url = ref('')
const audio = ref(false)

function stop() {
    recorder.stop()
    isRecording.value = false
    url.value = window.URL.createObjectURL(recorder.getBlob())
}
function send() {
    audio.value.stop()
    emit('voice', recorder.getBlob(), recordTime.value)
    emit('update:modelValue', false)
}
function cancel() {
    recorder.stop()
    audio.value.stop()
    window.URL.revokeObjectURL(url.value)
    url.value = ''
    recordTime.value = 0
    emit('update:modelValue', false)
}
function counter() {
    recordTime.value = recorder.currentTime | 0
    if(!isRecording.value) return
    setTimeout(() => {
        counter()
    }, 1000)
}
watchEffect(async () => {
    if(modelValue.value) {
        try{
            await recorder.start()
            isRecording.value = true
            counter()
        } catch(e) {
            emit('update:modelValue', false)
            throw e
        }
    }
})
onBeforeUnmount(() => {
    recorder.destroy()
})
</script>

<template>
    <div class="c-werbrtc-recorder" v-if="modelValue">
        <div class="c-webrtc-recorder-audio">
            <CAudio :url="url" ref="audio" :time="recordTime"></CAudio>
        </div>
        <div>
            <button @click="stop" v-if="isRecording">停止</button>    
            <button @click="send" v-if="!isRecording">发送</button>
            <button @click="cancel">取消</button>
        </div>
    </div>
</template>